<template>
  <svg :class="svgClass" aria-hidden="true" :style="styleSize" v-bind="$attrs">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script lang="ts">
import { computed, defineComponent } from "vue";

/**
 * v-bind="$attrs" 组件$attrs属性透传绑定到元素上
 * vue3.0中$lietens已被移除 现在事件监听器是 $attrs 的一部分
 * 文档说明：
 * https://v3.cn.vuejs.org/guide/migration/listeners-removed.html#_3-x-%E8%AF%AD%E6%B3%95
 */
export default defineComponent({
  name: "SvgIcon",
  inheritAttrs: false, // 组件上的$attrs不自动添加到组件根元素上 默认添加到组件根元素上
  props: {
    name: {
      type: String,
      require: true,
    },
    className: {
      type: String,
      default: "",
    },
    size: String,
  },
  setup(props) {
    const iconName = computed(() => `#icon-${props.name}`);
    // 添加类名 props.className外部传入自定义类名
    const svgClass = computed(() =>
      props.className ? `svg-icon ${props.className}` : "svg-icon"
    );
    // 添加icon大小
    const styleSize = computed(() => {
      const size: string = props.size ? `${props.size}px` : "1rem";
      return {
        fontSize: size,
        width: size,
        height: size,
      };
    });

    return {
      iconName,
      svgClass,
      styleSize,
    };
  },
});
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
